package com.xpm;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.xpm.activity.MultiTypeActivity;
import com.xpm.adapter.simple.GridViewAdapter;
import com.xpm.adapter.simple.ListViewAdapter;
import com.xpm.adapter.simple.RecycleViewBaseAdapter;
import com.xpm.adapter.simple.StaggerViewAdapter;
import com.xpm.base.BaseActivity;
import com.xpm.databinding.ActivityMainBinding;
import com.xpm.entity.DataProvider;
import com.xpm.entity.ItemBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 自动导包快捷键：ctrl+alt+o (auto import)
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private static final String TAG  = MainActivity.class.getSimpleName();

    RecyclerView recyclerView;
    SwipeRefreshLayout refreshLayout;

    private  List<ItemBean> mData;
    private RecycleViewBaseAdapter adapter;

    private Handler mHandler = new Handler();



    @Override
    protected ActivityMainBinding getBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }
    @Override
    protected void initView() {
        setTitle("RecycleView例子");
        // 获取RecycleView对象
        recyclerView = binding.recycleView;
        refreshLayout = binding.refresh;

        refreshLayout.setColorSchemeResources(R.color.colorPrimary,R.color.colorPrimaryDark,R.color.colorAccent);
        refreshLayout.setEnabled(true);
    }


    @Override
    protected void initData() {

        // 获取数据源,一般情况下在网上获取
        mData = new ArrayList<>();
        // 创建模拟数据
        for (int i = 0; i < DataProvider.icons.length; i++){
            ItemBean bean = new ItemBean();
            bean.icon =DataProvider.icons[i];
            bean.title = "标题"+i;
            mData.add(bean);
        }
        Log.i(TAG, "数据源："+mData.size());

        showList(true,false);



//        //创建适配器 ItemListViewAdapter 继承自 BaseAdapter
//        ItemListViewAdapter adapter = new ItemListViewAdapter();
//        binding.recycleView.setAdapter(adapter);
//        // 设置点击监听
//        adapter.setOnItemClickListener((bean, position) -> {
//            // 处理点击事件
//        });
//        // 设置长按监听
//        adapter.setOnItemLongClickListener((bean, position) -> {
//            // 处理长按事件
//            return true;
//        });
//        adapter.setData(mData);





    }

    @Override
    protected void initListener() {
        adapter.setOnItemClickListener(new RecycleViewBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Log.d(TAG,"点击事件："+position);
                Toast.makeText(getApplicationContext(),"点击事件："+position,Toast.LENGTH_SHORT).show();
            }
        });

        //设置下拉刷新时间
        refreshLayout.setOnRefreshListener(() -> {
             // 执行刷新数据的操作
            /**
             *  当我们在顶部下拉的时候，这个方法就会被触发
             *  但是这个方法是在mainThread中进行的，不能进行耗时操作，不然会导致界面卡顿
             *  一般情况下要去开启一个县城获取数据
             */
            ItemBean bean = new ItemBean();
            bean.icon = R.drawable.ic_launcher_background;
            bean.title = "标题"+System.currentTimeMillis();
            mData.add(0,bean);
            // 更新UI
            mHandler.postDelayed(()->{
                // 让刷新停止
                adapter.notifyDataSetChanged();
                refreshLayout.setRefreshing(false);
            },3000);

        });


        //设置加载更加（一般是分页加载数据）
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//        });
        if(adapter instanceof ListViewAdapter){
            ListViewAdapter mAdapter = (ListViewAdapter) adapter;
            mAdapter.setOnRefreshListener(new ListViewAdapter.OnRefreshListener() {

                @Override
                public void onUpPullRefresh(ListViewAdapter.LoadMoreViewHolder loaderMoreHolder) {
                    //这里面去加载更多的数据,同样,需要在子线程中完成,这里仅作演示

                    //更新UI
                    mHandler.postDelayed(()->{
                        Random random = new Random();

                        if (random.nextInt() % 2 == 0) {
                            ItemBean data = new ItemBean();
                            data.title = "我是新添加的数据...";
                            data.icon = R.mipmap.pic_09;
                            mData.add(data);

                            //这里要做两件事,一件是让刷新停止,另外一件则是要更新列表
                            mAdapter.notifyDataSetChanged();
                            loaderMoreHolder.update(loaderMoreHolder.LOADER_STATE_NORMAL);
                        } else {
                            loaderMoreHolder.update(loaderMoreHolder.LOADER_STATE_RELOAD);
                        }




                    },3000);
                }
            });



        }





    }


    /**
     * 加载菜单条目
     * @param menu The options menu in which you place your items.
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 菜单点击、选中时间
     * @param item The menu item that was selected.
     *
     * @return boolean
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        // ListView部分
        Log.d(TAG,"点击事件："+itemId);
        if(itemId == R.id.list_view_vertical){
            showList(true,false);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.list_view_vertical_reverse){
            showList(true,true);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.list_view_horizon){
            showList(false,false);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.list_view_horizon_reverse){
            showList(false,true);
            return super.onOptionsItemSelected(item);
        }


        // GridView部分
        if(itemId == R.id.grid_view_vertical){
            showGrid(true,false);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.grid_view_vertical_reverse){
            showGrid(true,true);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.grid_view_horizon){
            showGrid(false,false);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.grid_view_horizon_reverse){
            showGrid(false,true);
            return super.onOptionsItemSelected(item);
        }

        // StaggerView部分
        if(itemId == R.id.stagger_view_vertical){
            showStagger(true,false);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.stagger_view_vertical_reverse){
            showStagger(true,true);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.stagger_view_horizon){
            showStagger(false,false);
            return super.onOptionsItemSelected(item);
        }
        if(itemId == R.id.stagger_view_horizon_reverse){
            showStagger(false,true);
            return super.onOptionsItemSelected(item);
        }

        // 多种条目类型被点击
        if(itemId  == R.id.multiType_view){
            // 跳到新的Activity
            Intent intent = new Intent(this, MultiTypeActivity.class);
            startActivity(intent);
            return super.onOptionsItemSelected(item);
        }


        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置列表
     * @param isVertical 列表是否垂直
     * @param isReverse  列表是否反转
     */
    private void showList(boolean isVertical,boolean isReverse){
        // 基础使用
        // 1.设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // 1.1 设置方向
        layoutManager.setOrientation(isVertical?LinearLayoutManager.VERTICAL:LinearLayoutManager.HORIZONTAL);
        layoutManager.setReverseLayout(isReverse);
        // 1.2 给Recycle设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        // 2.创建适配器
        adapter = new ListViewAdapter(mData);
        recyclerView.setAdapter(adapter);
        // 初始化监听事件
        initListener();

    }
    /**
     * 设置grid
     * @param isVertical 列表是否垂直
     * @param isReverse  列表是否反转
     */
    private void showGrid(boolean isVertical,boolean isReverse){
        // 基础使用
        // 1.设置布局管理器
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        // 1.1 设置方向
        layoutManager.setOrientation(isVertical?GridLayoutManager.VERTICAL:GridLayoutManager.HORIZONTAL);
        layoutManager.setReverseLayout(isReverse);
        // 1.2 给Recycle设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        // 2.创建适配器
        adapter = new GridViewAdapter(mData);
        recyclerView.setAdapter(adapter);
        // 设置监听事件
        initListener();

    }

    /**
     * 设置瀑布流效果
     * @param isVertical 列表是否垂直
     * @param isReverse  列表是否反转
     */
    private void showStagger(boolean isVertical,boolean isReverse){
        // 基础使用
        // 1.1 设置布局管理器 spanCount => 列数，默认为1 orientation 方向
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,isVertical?StaggeredGridLayoutManager.VERTICAL:StaggeredGridLayoutManager.HORIZONTAL);
        layoutManager.setReverseLayout(isReverse);
        // 1.2 给Recycle设置布局管理器
        recyclerView.setLayoutManager(layoutManager);

        // 设置Adapter
        adapter = new StaggerViewAdapter(mData);
        recyclerView.setAdapter(adapter);
        // 设置监听事件
        initListener();
    }
}